define(function(require) {
	var $ = require("jquery1.7");
	var backManagerService = require("bean/backManagerService");
	var Confirmbox = require("confirmbox");
	var uploadify = require("uploadify");
	var utils = require("utils");
	var ui = require("ui");
	require("zTree");
	require("ztree-exedit");
	require("ztree-excheck");
	var isUserName = false;
	var ctx = utils.constants.ctx;	
    var allRoles = backManagerService.loadAllroles();
    var form = layui.form;
    var element = layui.element;
    var layer = layui.layer;
    var table=layui.table;
    var tablelin = table.render({
    	elem: '#demo'
    	    ,url : '/back/base/userData'
    	    ,cols: [[ //标题栏
    	      {checkbox: true}
    	      ,{field: 'username', title: '账号', width: 120}
    	      ,{field: 'nickname',title:'昵称',width:120}
    	      ,{field: 'iendtifyName', title: '身份', width: 100}
    	      ,{field:'groupName',title:'部门/班级', width:100}
    	      ,{field:'roleNameList',title:'已分配角色',width:160}
    	      ,{field:'establishDate',title:'创建时间',width:170}
    	      ,{field: '', title: '操作', templet:'#barDemo', width: 360}
    	    ]] 
    	    ,even: true
    	    ,page: true //是否显示分页
    	    ,limits: [8, 12, 15,18]
    	    ,limit: 8 //每页默认显示的数量
    	    ,id: "user_table"
    	  })
    	  
    table.on('tool(demo)',function(obj){
    	var layEvent = obj.event;
    	var data= obj.data;
    	var id= data.id;
    	var groupId= data.groupId;
    	var identityId=data.identityId;
    	
    	if(layEvent === 'edit'){   	
			//location.href =  ctx+"/back/base/userEdit?userId="+id;
    	}else if(layEvent === 'role'){
    		 $.post('/back/base/userRoleEditUI',{"id":id},function(str){
				  layer.open({
				    type: 1,
				    content: str,
				    title:'分配角色<span><font style="color:red">（组内角色不可修改）</font></span>'//注意，如果str是object，那么需要字符拼接。
				  });
				  form.render();
				});
    	}else if(layEvent === 'resource'){
    		
    		var data = '<div id="user_resource_tree" class="ztree" style="min-height:160px;"></div>';
    		
    		var roleResources; //来源于用户的角色权限
    		try{
    			roleResources = backManagerService.loadUserRolesResources(id);
    		} catch (e) {
    			alert("加载数据失败:" + e.message);
    			return;
    		}
    		$("#doc-modal-4 .am-modal-bd").html(data);
    		var updateRescourceCb;
    		if(updateRescourceCb == null){
	        	updateRescourceCb = layer.open({
	        		//type:1,
	        		title:'用户的权限资源',
	        		content:data
//	        		yes:function(){
//	        			var zTree = $.fn.zTree.getZTreeObj("user_resource_tree");
//						var nodes = zTree.getCheckedNodes(true);
//						var nodeIds = [];
//						for(var i=0; i<nodes.length; i++) {
//							var flag = true;
//							for(var j=0; j<roleResources.length; j++) {
//								if(nodes[i].id == roleResources[j].id){
//									flag = false;
//									break;
//								}
//							}
//							if(flag) {
//								nodeIds.push(nodes[i].id);
//							}
//						}		
//						try {
//
//							backManagerService.userAllotResource(roleId, nodeIds);
//							layer.alert('分配成功');
//					 		window.location.reload();
//					 	} catch (e){
//							layer.alert('分配失败！<br/>' + e.message);
//					 	}
	        		})
	        	}
                var user_resource_setting = {
					
					data : {
						simpleData :{
							enable :true,
							idKey : "id",
							pIdKey : "parentId" 
						}
						
					},
					check: {
						enable: true,
						chkStyle: "checkbox",
						chkDisabled : false
					},
					async : {
						enable : true,
						url : ctx + "/back/base/resource-json", 
						autoParam : ["id","name"]
					},
					
					view : {
						expandSpeed:"",
						selectedMulti: false		
					},
					edit : {
						enable : true,
						showRemoveBtn:false,
						showRenameBtn:false,
						drag: {
							isCopy: false,
							isMove: false
						}
					},
					callback : { //回调函数  
						onAsyncSuccess: function() {
							
//							ui.mask().hide();
							var zTree = $.fn.zTree.getZTreeObj("user_resource_tree");

							for(var i=0; i < roleResources.length; i++) {
								var node = zTree.getNodeByParam("id", roleResources[i].id);
								zTree.checkNode(node, true, false);
							}
							var nodes = zTree.getNodes();
							for(var i=0; i < nodes.length; i++) {
								zTree.setChkDisabled(nodes[i], true, true, true);
							}
						}
			        } 
			};
			$.fn.zTree.init($("#user_resource_tree"), user_resource_setting, []);
			//ui.mask().show("请稍候...");
	        	
	        }else if(layEvent ==='reset'){
	    		if(backManagerService.resetPassword(id)){
	    			alert("密码重置成功，重置密码为1");
	    		} else {
	    			alert("密码重置失败！请刷新页面后再试");
	    		}
	        	
	        }
    
        
	        
    		
    })
    
    form.on('submit(newRole_sumit)',function(data){
    	var userId = data.field.id;
    	var newRoleIds = [];
    	for(var name in data.field){//遍历对象属性名  	
    		if(name.indexOf("role")!=-1){
    			newRoleIds.push(name.substring(5,name.indexOf("]")))
			     delete data.field[name];						
		  }
    	}
    	 try{
				backManagerService.userAllotRole(userId, newRoleIds);
				alert("分配角色成功！");
				//this.hide();
				window.location.reload();
			} catch (e) {
				alert("分配角色失败:" + e.message);
				return;
			}
    })
	
    
    /*添加tab*/
    $(document).on("click",".add, .btn_update",function(){
    	var user_id = typeof($(this).attr("data"))=="undefined"?"0":$(this).attr("data");
		 element.tabDelete('marin-tab', user_id);
		  $.get("/back/base/userEdit?userId="+(user_id=="0"?"":user_id),function(requestData){
			  element.tabAdd('marin-tab', {
			        title: (user_id==0?"添加用户":"编辑用户")+'<i class="layui-icon layui-unselect layui-tab-close close_tab_btn" data="'+user_id+'">ဆ</i>' //强行加删除标志
			        ,content: requestData
			        ,id: user_id //实际使用一般是规定好的id，这里以时间戳模拟下
		      });
		      element.tabChange('marin-tab', user_id);
		      form.render();
		  })
    });
    
  //手动让tab删除
	  $(document).on("click",".close_tab_btn",function(){
		  element.tabDelete('marin-tab', $(this).attr("data"));
	  });
  
      

//		var form = layui.form;
//		form.render();
//		form.on("submit(user_sumit)",function(obj){
//			var user = obj.field
//			user.identityId = Number(user.identityId);
//			user.approval = 1;
////			console.log(user);
//			if (user.id == ""){
//				backManagerService.userAdd(user);
//		 		layer.alert('添加成功',function(){
//		 			location.href = ctx+"/back/base/userList";
//		 		});
//	 		} else {
//	 			backManagerService.userUpdate(user);
//		 		layer.alert('修改成功',function(){
//		 			location.href = ctx+"/back/base/userList";
//		 		});
//	 		}
//	 		
//			return false;
//		});
		
//  //取消添加或者编辑
//	  $(document).on("click","#p_quxiao",function(){
//		  window.history.back(); 
//			 
//		});
	
	var deleteUserList = function(){
    	
    	var checkStatus = layui.table.checkStatus('user_table');
		if (checkStatus.data.length===0) {
			layer.alert("请选择至少一个用户");
			return;
		}
		layer.confirm("确定要删除这些用户？",{icon: 3, title:'提示'},function(isOk){
			if(isOk){
				var data = checkStatus.data;
				var array = [];
				for(var i = 0; i<data.length;i++){
					array.push(data[i].id);   
				}
				if (array.length != 0) {
					try{
						ui.mask().show("请稍候...");
						backManagerService.userDelete(array);
						ui.mask().hide();
						layer.alert("删除成功",function(){						
							window.location.reload(true);
						});
					} catch (e) {
						ui.mask().hide();
						layer.alert("删除失败:"+e.message);
					}
				}
			}
		})
	
	
	}
	//删除用户列表
	$(document).on("click","#deleteUserList", deleteUserList);
	
	$("#user_m_group_d").hover(function(){
		$(this).show();
	}, function(){
		$(this).hide();
	});

	$("#user_m_group_name").on("click",function(){
		$("#user_m_group_d").show();
	});
	
	

	
	//zTree基本设置
	var user_group_setting = {
			
		data : {
			simpleData :{
				enable :true,
				idKey : "id",
				pIdKey : "parentId" 
			}
			
		},
		view : {
			expandSpeed:"",
			selectedMulti: false
			
		},
		edit : {
			enable : false
		},
		callback : { //回调函数  
			beforeClick: beforeClick_user_m_group,
			onClick: afterClick_user_m_group
		}
	};
	
	function beforeClick_user_m_group(treeId, treeNode, clickFlag){
		$("#user_m_group_name").val(treeNode.name);
		$("#user_m_group_name").focus();			
		$("#user_m_group_i").val(treeNode.id);
	}
	
	function afterClick_user_m_group(treeId, treeNode, clickFlag){
		$("#user_m_group_d").hide();
		
	}
	
	//加载用户组信息
	try{
		var groups = backManagerService.getGroupList(1);
		//var grades = backManagerService.getGroupList(2);//隐藏年级管理
		//groups = groups.concat(grades);
		$.fn.zTree.init($("#user_m_sortTree"), user_group_setting, groups);
	} catch (e) {
		blackBox.alert("加载身份失败:"+e.message);
	}
	
	
	//查询用户
	$("#searchBtn").bind("click",function(){
		var groupId = $("#user_m_group_i").val();
		var groupName = $("#user_m_group_name").val();
		var indentifyId = $("#ident_select").val();
		var username = $('#searchInfo').val();
		if(indentifyId==0||indentifyId==null){
			indentifyId="";
		}
		var searchContent = $("#searchInfo").val();
					
		table.reload('user_table', {
			  where: {
				  groupId:groupId,
				  groupName:groupName,
				  indentifyId:indentifyId,
				  username:username
			  } 
			  
			});
		
	});

	//用户的分配权限
	var updateRescourceCb;
	$(".btn_resource").bind("click",function(){
		var userId = $(this).attr("user_id").replace("user_", "");
		var data = '<div id="user_resource_tree" class="ztree" style="min-height:160px;"></div>';
		
		var roleResources; //来源于用户的角色权限
		try{
			roleResources = backManagerService.loadUserRolesResources(userId);
		} catch (e) {
			blackBox.alert("加载数据失败:" + e.message);
			return;
		}
		$("#doc-modal-4 .am-modal-bd").html(data);
		if(updateRescourceCb == null) {
			updateRescourceCb = new Confirmbox({
				
				trigger: '#user_resource_tree',
				title: "用户的权限资源",
				message: data,
				width : 450,
				confirmTpl: '',
		        cancelTpl: '',
				onConfirm: function() {
					
					var zTree = $.fn.zTree.getZTreeObj("user_resource_tree");
					var nodes = zTree.getCheckedNodes(true);
					var nodeIds = [];
					for(var i=0; i<nodes.length; i++) {
						var flag = true;
						for(var j=0; j<roleResources.length; j++) {
							if(nodes[i].id == roleResources[j].id){
								flag = false;
								break;
							}
						}
						if(flag) {
							nodeIds.push(nodes[i].id);
						}
					}	
					try {

						backManagerService.userAllotResource(roleId, nodeIds);
						blackBox.alert('分配成功');
				 		window.location.reload();
				 	} catch (e){
				 		blackBox.alert('分配失败！<br/>' + e.message);
				 	}
				}
			});
		} else {					
			updateRescourceCb.before('show',function() {

		       this.set('message', data);
		   });
		}
		updateRescourceCb.show();
		//zTree基本设置
		var user_resource_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				check: {
					enable: true,
					chkStyle: "checkbox",
					chkDisabled : false
				},
				async : {
					enable : true,
					url : ctx + "/back/base/resource-json", 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  
					onAsyncSuccess: function() {
						
						ui.mask().hide();
						var zTree = $.fn.zTree.getZTreeObj("user_resource_tree");

						for(var i=0; i < roleResources.length; i++) {
							var node = zTree.getNodeByParam("id", roleResources[i].id);
							zTree.checkNode(node, true, false);
						}
						var nodes = zTree.getNodes();
						for(var i=0; i < nodes.length; i++) {
							zTree.setChkDisabled(nodes[i], true, true, true);
						}
					}
		        } 
		};
		$.fn.zTree.init($("#user_resource_tree"), user_resource_setting, []);
	});
	
	//重置用密码
	$(".btn_key_delete").bind("click",function(){
		var userId = $(this).prev().attr("user_id").replace("user_","");
		if(backManagerService.resetPassword(userId)){
			blackBox.alert("密码重置成功，重置密码为1");
		} else {
			blackBox.alert("密码重置失败！请刷新页面后再试");
		}
	});
	
	//导入用户
	$(document).on("click","#importUser",function(){
		$.post(ctx + "/back/base/userimportUI",function(data){
			var importCb=layer.open({
				    type: 1,
				    content: data,
				    title:'批量导入用户'//注意，如果str是object，那么需要字符拼接。
				  });
			form.render();
		})
		$("#importFinish,#importCancel").on("click",function(){
			$("#doc-modal-1").find("a.am-close-spin").trigger("click");
		})
		
	})
		
    //导出用户
	$("#exportUser").bind("click",function(){
		if(!window.confirm("确定要导出所有用户？")){
			return;
		}
		$.post(ctx+"/back/base/exportUser",function(data){
//			console.log(data);
			ui.mask("body").hide();
			window.open(ctx + data);
		});
	});
	
	//班级部门
	var addGroupCb;
	$("#setClassAndGroup").click(function(){
		var checkStatus = layui.table.checkStatus('user_table');
		if (checkStatus.data.length===0) {
			layer.alert("请选择用户");
			return;
		}
		var data = checkStatus.data;
		var array = [];
		for(var i = 0; i<data.length;i++){
			array.push(data[i].id);   
		}
//		$('input[name=items]:checkbox:checked').each(function() {
//		    	
//			var id = $(this).attr("id").replace("user_", "");
//			array.push(id);   
//		});
		
		var data = '<div id="user_group_tree" class="ztree" style="height:200px;"></div>';
				
		if(addGroupCb == null) {
			
			addGroupCb =  layer.open({
        		title:'用户的部门或者班级',
        		content:data,
        		area: ['450px', '450px'],
        		yes:function(){
        			var zTree = $.fn.zTree.getZTreeObj("user_group_tree");
					var nodes = zTree.getCheckedNodes(true);	
					if(nodes.length == 0) {
						layer.alert("请选择部门或者班级！");
						return;
					}
					
					try {
							backManagerService.setUserGroup(array, nodes[0].id);
							layer.alert('分配成功',function(){
								
								window.location.reload();
							});
						
				 	}catch (e){
						layer.alert('分配失败！<br/>' + e.message);
        		  }
        		}
        	});
		}
		//zTree基本设置
		var user_resource_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				check: {
					enable: true,
					chkStyle: "radio",
					radioType:"all"
				},
				async : {
					enable : true,
					url :  ctx + "/back/base/group-json?sortId=-1", 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  
					onAsyncSuccess: function() {
						
						var zTree = $.fn.zTree.getZTreeObj("user_group_tree");
						var nodes = zTree.getNodes();
						for(var i=0; i < nodes.length; i++) {
							if(nodes[i].sortId == 2 && nodes[i].isParent){
								zTree.setChkDisabled(nodes[i], true);
							}
						}
						ui.mask().hide();
					}
		        } 
		};
		$.fn.zTree.init($("#user_group_tree"), user_resource_setting, []);
		ui.mask().show("请稍候...");
		
	})
	
	
	$("a[id^=socreUpdate_]").bind("dblclick",function(){
		
		var id = $(this).attr("id").replace("socreUpdate_","");
		var score = $(this).html();
		
		var data = '<div><input id="updateValue_' + id + '" value="'+score+'"></div>';
		
		var updateScoreCb = new Confirmbox({
			
			trigger: '',
			title: "修改积分",
			message: data,
			width : 450,
			onConfirm: function() {
				var tempScore = $("#updateValue_"+id).val();
				var reg = /^\+?[1-9][0-9]*$/;
				if(!reg.test(tempScore)){
					blackBox. alert("请输入数字!");
				    return ;
				}
				if(tempScore != score) {
					backManagerService.updateUserScore(id,tempScore);
					blackBox.alert("修改成功！");
				}
				window.location.reload();
			}
		});
		updateScoreCb.show();
		
	})
/**************************************添加和更新用户信息js*****************************************************/

	//添加用户方法
	var userSubmit = function (){
		var userId = $("#user_id").val();
	    var username = $("#user_username").val();
		var	nickname = $("#user_nickname").val();
		var	identityId = $("#user_identity").val();
		var	email = $("#user_email").val();
		var	phone = $("#user_phone").val();
		var password = $("#user_password").val();
		var rePassword = $("#user_password-confirmation").val();
		if(username == ""){
			
			$("#user_username").focus();
			$("#am-userName").css("color","#F37B1D");
			$("#am-userName").html("*用户名不能为空");
//			$("#user_username").trigger("focus");
//			$("#user_username").trigger("blur");
			return false;
		}
		if(password == ""){
			$("#user_password").focus();
			$("#am-password-noti").css("color","#F37B1D");
			$("#am-password-noti").html("*密码不能为空");
			return false;
		}
		if(rePassword == ""){
			
			$("#user_password-confirmation").focus();
			$("#am-repeat-psw").css("color","#F37B1D");
			return false;
		}
		
	 	if(nickname == "" ){
	 		$("#user_nickname").focus();
	 		$("#am-nickname-noti").css("color","#F37B1D");
			return false;
		}
	 	var reg1 = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.(?:com|cn)$/;
	 	if(email == ""){
	 		$("#user_email").focus();
	 		$("#am-email-notice").css("color","#F37B1D");
	 		$("#am-email-notice").html("*邮箱不能为空");
			return false;
	 	}else if(!reg1.test(email)){
	 		$("#user_email").focus();
	 		$("#am-email-notice").css("color","#F37B1D");
	 		$("#am-email-notice").html("*邮箱格式不对，邮箱格式应如：xxx@163.com");
	 	}
	 	
	 	//判断电话号码是否为空或正确与否
	 	var a=/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$|(^1[3|4|5|7|8]\d{9}$)/;
	 	if(phone == ""){
	 		$("#user_phone").focus();
	 		$("#am-phone-noti").css("color","#F37B1D");
	 		$("#am-phone-noti").html("*电话不能为空");
	 		return false;
	 	}else if(!a.test(phone)){
	 		$("#user_phone").val("");
	 		$("#user_phone").focus();
	 		$("#am-phone-noti").css("color","#F37B1D");
	 		$("#am-phone-noti").html("*电话格式不对，请输入正确的电话号码，\n\n如：0591-6487256，15005059587");
	 	}

	 	var user = {
	 			id : userId,
    			username : username,
    			nickname : nickname,
    			identityId : identityId,
    			email : email,
    			phoneNumber : phone,
    			approval : 1,
    			password : password
    		};
	 	
	 	try {
	 		if (userId == ""){
    	 		backManagerService.userAdd(user);
    	 		layer.alert('添加成功');
	 		} else {
    	 		backManagerService.userUpdate(user);
    	 		layer.alert('修改成功');
	 		}
	 		location.href = ctx+"/back/base/userList";
	 	} catch (e){
			alert(e.message);
	 	}
	}
//	$("#userSubmit").bind("click",userSubmit);
	
	$("#user_username").blur(function(){
		var username = $(this).val();
		if (username == "") {
			$("#user_username").focus();
			$("#am-userName").css("color","#F37B1D");
			$("#am-userName").html("*用户名不能为空");
		} else {
			$("#am-userName").css("color","#333");
			$("#am-userName").html("*必填，不可重复");
		}
	});
	
	$("#user_password").blur(function(){
		var password = $(this).val();
		if (password == "") {
			$("#user_password").focus();
			$("#am-password-noti").css("color","#F37B1D");
			$("#am-password-noti").html("*密码不能为空");
		} else {
			if(password.length < 6){
				$("#user_password").focus();
				$("#am-password-noti").css("color","#F37B1D");
				$("#am-password-noti").html("*密码长度不能小于6");
			}else{
				$("#am-password-noti").css("color","#333");
				$("#am-password-noti").html("*必填，请输入由数字和字母组成的6-16位密码");
			}
		}
		
	});
	
	//验证密码与重复密码是否一致
	$(document).on("change","#user_password-confirmation",function(){
		var password = $("#user_password").val();
		var rePassword = $(this).val();
		if(password == ""){
			$("#user_password").focus();
			$("#am-password-noti").css("color","#F37B1D");
			$("#am-password-noti").html("*密码不能为空");
			return false;
		}
		if(rePassword == ""){
			$("#user_password-confirmation").focus();
			$("#am-repeat-psw").css("color","#F37B1D");
			return false;
		}
		if (password != rePassword) {
			$("#user_password-confirmation").val("");
			$("#user_password-confirmation").focus();
			$("#am-repeat-psw").css("color","#F37B1D");
			$("#am-repeat-psw").html("*重复密码与密码不一致");
		}else{
			$("#am-repeat-psw").css("color","#333");
			$("#am-repeat-psw").html("*必填，请再输入一遍密码");
		}
	});
	
	$("#user_nickname").blur(function(){
		var nickname = $(this).val();
		if (nickname == "") {
			$("#user_nickname").focus();
			$("#am-nickname-noti").css("color","#F37B1D");
			$("#am-nickname-noti").html("*昵称不能为空");
		} else if(nickname.length<6){
			$("#am-nickname-noti").css("color","#333");
			$("#am-nickname-noti").html("*长度大于6个字符");
		}else{
			$("#am-nickname-noti").html("*可使用");
		}
	});
	
	$("#user_email").blur(function(){
		var email = $(this).val();
//		var reg1 = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.(?:com|cn)$/;//隐藏规则
		if (email == "") {
			$("#user_email").focus();
			$("#am-email-notice").css("color","#F37B1D");
			$("#am-email-notice").html("*邮箱不能为空");
        	} 
			//else {
//			if(!reg1.test(email)){
//		 		$("#user_email").focus();
//		 		$("#am-email-notice").css("color","#F37B1D");
//		 		$("#am-email-notice").html("*邮箱格式不对，邮箱格式应如：xxx@163.com");
//		 	}else{
//		 		$("#am-email-notice").css("color","#333");
//		 		$("#am-email-notice").html("*必填");
//		 	}
//		}
	});
	
	$("#user_phone").blur(function(){
		var phone = $(this).val();
		var a=/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$|(^1[3|4|5|7|8]\d{9}$)/;
	 	if(phone == ""){
	 		$("#user_phone").focus();
	 		$("#am-phone-noti").css("color","#F37B1D");
	 		$("#am-phone-noti").html("*手机号码不能为空");
	 		return false;
	 	}
//	 	else{
//	 		if(!a.test(phone)){
//	 			$("#user_phone").val("");
//	 			$("#user_phone").focus();
//	 			$("#am-phone-noti").css("color","#F37B1D");
//	 			$("#am-phone-noti").html("*电话格式不对，请输入正确的电话号码，如：0591-6487256，15005059587");
//	 		}
//	 		else{
//	 			$("#am-phone-noti").css("color","#333");
//				$("#am-phone-noti").html("*必填");
//	 		}
//	 	}
	});
	
//	var form = layui.form;
	form.render();
	form.on("submit(user_sumit)",function(obj){
		var user = obj.field;
		user.approval = 1;
		var res;
		if(!isUserName){
			if(!backManagerService.repeatUsername(user.id,user.username)){
				$("#am-userName").html("*用户名已存在");
				layer.msg("用户名已存在!",{icon:7});
				return false;
			}
		}

		//密码检验
		if(!(user.password == "" && user.repassword == "")){
			if (user.password.length < 6) {
				layer.msg("密码长度不能小于6位！",{icon:5});
				return false;
			}
			if(!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/.test(user.password)){
				layer.msg("密码必须包含数字和英文!",{icon:5});
				return false;
			}
			if(user.repassword!=user.password){
				layer.msg("两次密码输入不一致",{icon:5});
				return false;
			}
		}
		
		//昵称检验
		if(user.nickname.length<2){
			layer.msg("昵称不能少于2个字符",{icon:5});
			return false;
		}

		//邮箱格式检验
		if(!/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(user.email)&&user.email!=""){
			layer.msg("邮箱格式不正确",{icon:5});
			return false;
		}

		//手机号码检验
		if(!/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/.test(user.phoneNumber)&&user.phoneNumber!=""){
			layer.msg("手机号码不正确",{icon:5});
			return false;
		}
		if (user.id == ""){
			layer.confirm("是否保存？",{
				yes:function(){
					res = backManagerService.userAdd(user);
					if(res==false){
						layer.msg("用户名已存在",{icon:5});
						return false;
					}
			 		layer.alert('添加成功',function(){
			 			location.href = ctx+"/back/base/userList";
			 		});
				}
			});
 		} else {
 			layer.confirm("确定保存？",{
				yes:function(){
					res = backManagerService.userUpdate(user);
		 			if(res==false){
						layer.msg("用户名已存在",{icon:5});
						return false;
					}
			 		layer.alert('修改成功',function(){
			 			location.href = ctx+"/back/base/userList";
			 		});
				}
			});
 		}
 		
		return false;
	});
	$(document).on("click","#p_quxiao",function(){
		
		location.href =  ctx+"/back/base/userList";
	});
	
	function formCheck(user_id){
		//用户名输入检验
		$("#user_username").blur(function(){
			var username = $(this).val();
			if (username == "") {
				$("#am-userName").css("color","#F37B1D");
				$("#am-userName").html("*用户名不能为空");
				layer.msg("用户名不能为空!",{icon:7});
			} else {
				if(!backManagerService.repeatUsername(user_id,username)){
					$("#am-userName").html("*用户名已存在");
					layer.msg("用户名已存在!",{icon:7});
				}else{
					$("#am-userName").css("color","#333");
					$("#am-userName").html("*必填，不可重复");
					isUserName = true;
				}
			}
		});
	}
	
});